<!--
  Copyright JS Foundation and other contributors, http://js.foundation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- WebSocket Input Node -->
<script type="text/html" data-template-name="websocket in">
    <div class="form-row">
        <label for="node-input-mode"><i class="fa fa-dot-circle-o"></i> <span data-i18n="websocket.label.type"></span></label>
        <select id="node-input-mode">
            <option value="server" data-i18n="websocket.listenon"></option>
            <option value="client" data-i18n="websocket.connectto"></option>
        </select>
    </div>
    <div class="form-row" id="websocket-server-row">
        <label for="node-input-server"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
        <input type="text" id="node-input-server">
    </div>
    <div class="form-row" id="websocket-client-row">
        <label for="node-input-client"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
        <input type="text" id="node-input-client">
    </div>
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>
</script>

<script type="text/javascript">

(function() {

    const headerTypes = [
        /*
        { value: "Accept", label: "Accept", hasValue: false },
        { value: "Accept-Encoding", label: "Accept-Encoding", hasValue: false },
        { value: "Accept-Language", label: "Accept-Language", hasValue: false },
        */
        { value: "Authorization", label: "Authorization", hasValue: false },
        /*
        { value: "Content-Type", label: "Content-Type", hasValue: false },
        { value: "Cache-Control", label: "Cache-Control", hasValue: false },
        */
        { value: "User-Agent", label: "User-Agent", hasValue: false },
        /*
        { value: "Location", label: "Location", hasValue: false },
        */
        { value: "other", label: RED._("node-red:httpin.label.other"),
          hasValue: true, icon: "red/images/typedInput/az.svg" },
    ]

    const headerOptions = {};
    const defaultOptions = [
        { value: "other", label: RED._("node-red:httpin.label.other"),
          hasValue: true, icon: "red/images/typedInput/az.svg" },
        "env",
    ];
    /*
    headerOptions["accept"] = [
        { value: "text/plain", label: "text/plain", hasValue: false },
        { value: "text/html", label: "text/html", hasValue: false },
        { value: "application/json", label: "application/json", hasValue: false },
        { value: "application/xml", label: "application/xml", hasValue: false },
        ...defaultOptions,
    ];
    
    headerOptions["accept-encoding"] = [
        { value: "gzip", label: "gzip", hasValue: false },
        { value: "deflate", label: "deflate", hasValue: false },
        { value: "compress", label: "compress", hasValue: false },
        { value: "br", label: "br", hasValue: false },
        { value: "gzip, deflate", label: "gzip, deflate", hasValue: false },
        { value: "gzip, deflate, br", label: "gzip, deflate, br", hasValue: false },
        ...defaultOptions,
    ];
    headerOptions["accept-language"] = [
        { value: "*", label: "*", hasValue: false },
        { value: "en-GB, en-US, en;q=0.9", label: "en-GB, en-US, en;q=0.9", hasValue: false },
        { value: "de-AT, de-DE;q=0.9, en;q=0.5", label: "de-AT, de-DE;q=0.9, en;q=0.5", hasValue: false },
        { value: "es-mx,es,en;q=0.5", label: "es-mx,es,en;q=0.5", hasValue: false },
        { value: "fr-CH, fr;q=0.9, en;q=0.8", label: "fr-CH, fr;q=0.9, en;q=0.8", hasValue: false },
        { value: "zh-CN, zh-TW; q = 0.9, zh-HK; q = 0.8, zh; q = 0.7, en; q = 0.6", label: "zh-CN, zh-TW; q = 0.9, zh-HK; q = 0.8, zh; q = 0.7, en; q = 0.6", hasValue: false },
        { value: "ja-JP, jp", label: "ja-JP, jp", hasValue: false },
        ...defaultOptions,
    ];
    headerOptions["content-type"] = [
        { value: "text/css", label: "text/css", hasValue: false },
        { value: "text/plain", label: "text/plain", hasValue: false },
        { value: "text/html", label: "text/html", hasValue: false },
        { value: "application/json", label: "application/json", hasValue: false },
        { value: "application/octet-stream", label: "application/octet-stream", hasValue: false },
        { value: "application/pdf", label: "application/pdf", hasValue: false },
        { value: "application/xml", label: "application/xml", hasValue: false },
        { value: "application/zip", label: "application/zip", hasValue: false },
        { value: "multipart/form-data", label: "multipart/form-data", hasValue: false },
        { value: "audio/aac", label: "audio/aac", hasValue: false },
        { value: "audio/ac3", label: "audio/ac3", hasValue: false },
        { value: "audio/basic", label: "audio/basic", hasValue: false },
        { value: "audio/mp4", label: "audio/mp4", hasValue: false },
        { value: "audio/ogg", label: "audio/ogg", hasValue: false },
        { value: "image/bmp", label: "image/bmp", hasValue: false },
        { value: "image/gif", label: "image/gif", hasValue: false },
        { value: "image/jpeg", label: "image/jpeg", hasValue: false },
        { value: "image/png", label: "image/png", hasValue: false },
        { value: "image/tiff", label: "image/tiff", hasValue: false },
        ...defaultOptions,
    ];
    headerOptions["cache-control"] = [
        { value: "max-age=0", label: "max-age=0", hasValue: false },
        { value: "max-age=86400", label: "max-age=86400", hasValue: false },
        { value: "no-cache", label: "no-cache", hasValue: false },
        ...defaultOptions,
    ];
    */
    headerOptions["user-agent"] = [
        { value: "Mozilla/5.0", label: "Mozilla/5.0", hasValue: false },
        ...defaultOptions,
    ];

    function getHeaderOptions(headerName) {
        const lc = (headerName || "").toLowerCase();
        let opts = headerOptions[lc];
        return opts || defaultOptions;
    }

    function ws_oneditprepare() {
        $("#websocket-client-row").hide();
        $("#node-input-mode").on("change", function() {
            if ( $("#node-input-mode").val() === 'client') {
                $("#websocket-server-row").hide();
                $("#websocket-client-row").show();
            }
            else {
                $("#websocket-server-row").show();
                $("#websocket-client-row").hide();
            }
        });

        if (this.client) {
            $("#node-input-mode").val('client').change();
        }
        else {
            $("#node-input-mode").val('server').change();
        }
    }

    function ws_oneditsave() {
        if ($("#node-input-mode").val() === 'client') {
            $("#node-input-server").append('<option value="">Dummy</option>');
            $("#node-input-server").val('');
        }
        else {
            $("#node-input-client").append('<option value="">Dummy</option>');
            $("#node-input-client").val('');
        }
    }

    function ws_label() {
        var nodeid = (this.client)?this.client:this.server;
        var wsNode = RED.nodes.node(nodeid);
        return this.name||(wsNode?"[ws] "+wsNode.label():"websocket");
    }

    function ws_validateserver() {
        if ($("#node-input-mode").val() === 'client' || (this.client && !this.server)) {
            return true;
        }
        else {
            if (RED.nodes.node(this.server) != null) {
                return true;
            }
            return RED._("node-red:websocket.errors.missing-server");
        }
    }

    function ws_validateclient() {
        if ($("#node-input-mode").val() === 'client' || (this.client && !this.server)) {
            if (RED.nodes.node(this.client) != null) {
                return true;
            }
            return RED._("node-red:websocket.errors.missing-client");
        }
        else {
            return true;
        }
    }

    RED.nodes.registerType('websocket in',{
        category: 'network',
        defaults: {
            name: {value:""},
            server: {type:"websocket-listener", validate: ws_validateserver},
            client: {type:"websocket-client", validate: ws_validateclient}
        },
        color:"rgb(215, 215, 160)",
        inputs:0,
        outputs:1,
        icon: "white-globe.svg",
        labelStyle: function() {
            return this.name?"node_label_italic":"";
        },
        label: ws_label,
        oneditsave: ws_oneditsave,
        oneditprepare: ws_oneditprepare
    });

    RED.nodes.registerType('websocket out',{
        category: 'network',
        defaults: {
            name: {value:""},
            server: {type:"websocket-listener", validate: ws_validateserver},
            client: {type:"websocket-client", validate: ws_validateclient}
        },
        color:"rgb(215, 215, 160)",
        inputs:1,
        outputs:0,
        icon: "white-globe.svg",
        align: "right",
        labelStyle: function() {
            return this.name?"node_label_italic":"";
        },
        label: ws_label,
        oneditsave: ws_oneditsave,
        oneditprepare: ws_oneditprepare
    });

    RED.nodes.registerType('websocket-listener',{
        category: 'config',
        defaults: {
            path: {value:"",required:true,
                   label:RED._("node-red:websocket.label.path"),
                   validate:RED.validators.regex(/^((?!\/debug\/ws).)*$/)},
            wholemsg: {value:"false"}
        },
        inputs:0,
        outputs:0,
        label: function() {
            var root = RED.settings.httpNodeRoot;
            if (root.slice(-1) != "/") {
                root = root+"/";
            }
            if (this.path) {
                if (this.path.charAt(0) == "/") {
                    root += this.path.slice(1);
                } else {
                    root += this.path;
                }
            }
            return root;
        },
        oneditprepare: function() {
            var root = RED.settings.httpNodeRoot;
            if (root.slice(-1) == "/") {
                root = root.slice(0,-1);
            }
            if (root === "") {
                $("#node-config-ws-tip").hide();
            } else {
                $("#node-config-ws-path").html(RED._("node-red:websocket.tip.path2", { path: root }));
                $("#node-config-ws-tip").show();
            }
        }
    });

    RED.nodes.registerType('websocket-client',{
        category: 'config',
        defaults: {
            path: {
                value:"",required:true,
                label:RED._("node-red:websocket.label.path"),
                validate:RED.validators.regex(/^((?!\/debug\/ws).)*$/)},
            tls: {type:"tls-config",required: false},
            wholemsg: {value:"false"},
            hb: {
                value: "",
                label:RED._("node-red:websocket.sendheartbeat"),
                validate: RED.validators.number(/*blank allowed*/true) },
            subprotocol: {value:"",required: false},
            headers: { value: [] }
        },
        inputs:0,
        outputs:0,
        label: function() {
            return this.path;
        },
        oneditprepare: function() {

            const node = this;

            $("#node-config-input-path").on("change keyup paste",function() {
                $(".node-config-row-tls").toggle(/^wss:/i.test($(this).val()))
            });
            $("#node-config-input-path").change();

            var heartbeatActive = (this.hb && this.hb != "0");
            $("#node-config-input-hb-cb").prop("checked",heartbeatActive);
            $("#node-config-input-hb-cb").on("change", function(evt) {
                $("#node-config-input-hb-row").toggle(this.checked);
            })
            $("#node-config-input-hb-cb").trigger("change");
            if (!heartbeatActive) {
                $("#node-config-input-hb").val("");
            }

            const hasMatch = function (arr, value) {
                return arr.some(function (ht) {
                    return ht.value === value
                });
            }

            const headerList = $("#node-input-headers-container").css('min-height', '150px').css('min-width', '450px').editableList({
                addItem: function (container, i, header) {
                    const row = $('<div/>').css({
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        display: 'flex'
                    }).appendTo(container);
                    const propertNameCell = $('<div/>').css({ 'flex-grow': 1 }).appendTo(row);
                    const propertyName = $('<input/>', { class: "node-input-header-name", type: "text", style: "width: 100%" })
                        .appendTo(propertNameCell)
                        .typedInput({ types: headerTypes });

                    const propertyValueCell = $('<div/>').css({ 'flex-grow': 1, 'margin-left': '10px' }).appendTo(row);
                    const propertyValue = $('<input/>', { class: "node-input-header-value", type: "text", style: "width: 100%" })
                        .appendTo(propertyValueCell)
                        .typedInput({
                            types: getHeaderOptions(header.keyType)
                        });

                    const setup = function(_header) {
                        const headerTypeIsAPreset = function(h) {return hasMatch(headerTypes, h) };
                        const headerValueIsAPreset = function(h, v) {return hasMatch(getHeaderOptions(h), v) };

                        const {keyType, keyValue, valueType, valueValue} = header;

                        if(keyType == "other") {
                            propertyName.typedInput('type', keyType);
                            propertyName.typedInput('value', keyValue);
                        } else if (headerTypeIsAPreset(keyType)) {
                            propertyName.typedInput('type', keyType);
                        } else {
                            propertyName.typedInput('type', "other");
                            propertyName.typedInput('value', keyValue);
                        }

                        if(valueType == "other" || valueType == "env" ) {
                            propertyValue.typedInput('type', valueType);
                            propertyValue.typedInput('value', valueValue);
                        } else if (headerValueIsAPreset(propertyName.typedInput('type'), valueType)) {
                            propertyValue.typedInput('type', valueType);
                        } else {
                            propertyValue.typedInput('type', "other");
                            propertyValue.typedInput('value', valueValue);
                        }
                    }
                    setup(header);

                    propertyName.on('change', function (event) {
                        propertyValue.typedInput('types', getHeaderOptions(propertyName.typedInput('type')));
                    });
                
                },
                sortable: true,
                removable: true
            });
            if (node.headers) {
                for (let index = 0; index < node.headers.length; index++) {
                    const element = node.headers[index];
                    headerList.editableList('addItem', node.headers[index]);
                }
            }
        },
        oneditsave: function() {
            
            const node = this;

            if (!/^wss:/i.test($("#node-config-input-path").val())) {
                $("#node-config-input-tls").val("_ADD_");
            }
            if (!$("#node-config-input-hb-cb").prop("checked")) {
                $("#node-config-input-hb").val("0");
            }

            const headers = $("#node-input-headers-container").editableList('items');
            
            node.headers = [];
            headers.each(function(i) {
                const header = $(this);
                const keyType = header.find(".node-input-header-name").typedInput('type');
                const keyValue = header.find(".node-input-header-name").typedInput('value');
                const valueType = header.find(".node-input-header-value").typedInput('type');
                const valueValue = header.find(".node-input-header-value").typedInput('value');
                node.headers.push({
                    keyType, keyValue, valueType, valueValue
                })
                
            });
        },
        oneditresize: function(size) {
            const dlg = $("#dialog-form");
            const expandRow = dlg.find('.node-input-headers-container-row');
            let height = dlg.height() - 5;
            if(expandRow && expandRow.length){
                const siblingRows = dlg.find('> .form-row:not(.node-input-headers-container-row)');
                for (let i = 0; i < siblingRows.size(); i++) {
                    const cr = $(siblingRows[i]);
                    if(cr.is(":visible"))
                        height -= cr.outerHeight(true);
                }
                $("#node-input-headers-container").editableList('height',height);
            } 
        }
    });

})();
</script>

<!-- WebSocket out Node -->
<script type="text/html" data-template-name="websocket out">
    <div class="form-row">
        <label for="node-input-mode"><i class="fa fa-dot-circle-o"></i> <span data-i18n="websocket.label.type"></span></label>
        <select id="node-input-mode">
            <option value="server" data-i18n="websocket.listenon"></option>
            <option value="client" data-i18n="websocket.connectto"></option>
        </select>
    </div>
    <div class="form-row" id="websocket-server-row">
        <label for="node-input-server"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
        <input type="text" id="node-input-server">
    </div>
    <div class="form-row" id="websocket-client-row">
        <label for="node-input-client"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
        <input type="text" id="node-input-client">
    </div>
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>
</script>

<!-- WebSocket Server configuration node -->
<script type="text/html" data-template-name="websocket-listener">
    <div class="form-row">
        <label for="node-config-input-path"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
        <input id="node-config-input-path" type="text" placeholder="/ws/example">
    </div>
    <div class="form-row">
        <label for="node-config-input-wholemsg" data-i18n="websocket.sendrec"></label>
        <select type="text" id="node-config-input-wholemsg" style="width: 70%;">
            <option value="false" data-i18n="websocket.payload"></option>
            <option value="true" data-i18n="websocket.message"></option>
        </select>
    </div>
    <div class="form-tips">
        <span data-i18n="[html]websocket.tip.path1"></span>
        <p id="node-config-ws-tip"><span id="node-config-ws-path"></span></p>
    </div>
</script>

<!-- WebSocket Client configuration node -->
<script type="text/html" data-template-name="websocket-client">
    <div class="form-row">
        <label for="node-config-input-path"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
        <input id="node-config-input-path" type="text" placeholder="ws://example.com/ws">
    </div>
    <div class="form-row node-config-row-tls hide">
        <label for="node-config-input-tls" data-i18n="httpin.tls-config"></label>
        <input type="text" id="node-config-input-tls">
    </div>
    <div class="form-row">
        <label for="node-config-input-subprotocol"><i class="fa fa-tag"></i> <span data-i18n="websocket.label.subprotocol"></span></label>
        <input type="text" id="node-config-input-subprotocol">
    </div>
    <div class="form-row">
        <label for="node-config-input-wholemsg" data-i18n="websocket.sendrec"></label>
        <select type="text" id="node-config-input-wholemsg" style="width: 70%;">
            <option value="false" data-i18n="websocket.payload"></option>
            <option value="true" data-i18n="websocket.message"></option>
        </select>
    </div>
    <div class="form-row" style="display: flex; align-items: center; min-height: 34px">
        <label for="node-config-input-hb-cb" data-i18n="websocket.sendheartbeat"></label>
        <input type="checkbox" style="margin: 0 8px; width:auto" id="node-config-input-hb-cb">
        <span id="node-config-input-hb-row" class="hide" >
            <input type="text" style="width: 70px; margin-right: 3px" id="node-config-input-hb">
            <span  data-i18n="inject.seconds"></span>
        </span>
    </div>
    <div class="form-row" style="margin-bottom:0;">
        <label><i class="fa fa-list"></i> <span data-i18n="httpin.label.headers"></span></label>
    </div>
    <div class="form-row node-input-headers-container-row">
        <ol id="node-input-headers-container"></ol>
    </div>
    <div class="form-tips">
        <p><span data-i18n="[html]websocket.tip.url1"></span></p>
        <p><span data-i18n="[html]websocket.tip.url2"></span></p>
        <span data-i18n="[html]websocket.tip.headers"></span>
    </div>
</script>
